#!/bin/bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH

# Check if user is root
if [ $(id -u) != "0" ]; then
    echo "Error: You must be root to run this script"
    exit 1
fi

cur_dir=$(pwd)
action=$1
shopt -s extglob
Upgrade_Date=$(date +"%Y%m%d%H%M%S")
MemTotal=`free -m | grep Mem | awk '{print  $2}'`

. moodle.conf
. include/main.sh
. include/upgrade_nginx.sh
. include/upgrade_mariadb.sh
. include/upgrade_php.sh
. include/upgrade_moodle.sh

Get_Dist_Name

Display_Upgrade_Menu()
{
    echo -e " \e[0;33mYou have 5 options for Upgrade.\e[0m"
    echo -e "   \e[0;31m1\e[0m: Upgrade Nginx"
    echo -e "   \e[0;31m2\e[0m: Upgrade MariaDB"
    echo -e "   \e[0;31m3\e[0m: Upgrade PHP"
    echo -e "   \e[0;31m4\e[0m: Upgrade Moodle"
    echo -e "   \e[0;31mexit\e[0m: Exit current script"
    echo "-------------------------------------"
    read -p "Enter your choice (1, 2, 3, 4 or exit): " action
}

clear
echo "+-----------------------------------------------------------------------+"
echo "|            Upgrade script for Moodle , Written by Hongm               |"
echo "+-----------------------------------------------------------------------+"
echo "|         A tool to upgrade Nginx,Mariadb,PHP for Moodle service          |"
echo "+-----------------------------------------------------------------------+"

if [ "${action}" == "" ]; then
    Display_Upgrade_Menu
fi

case "${action}" in
    1|[nN][gG][iI][nN][xX])
        Upgrade_Nginx 2>&1 | tee /root/upgrade_nginx${Upgrade_Date}.log
        ;;
    2|[mM][aA][rR][iI][aA][dD][bB])
        Upgrade_MariaDB 2>&1 | tee /root/upgrade_mariadb${Upgrade_Date}.log
        ;;
    3|[pP][hP][pP])
        Upgrade_PHP 2>&1 | tee /root/upgrade_php${Upgrade_Date}.log
        ;;
    4|[mM][oO][oO][dD][lL][eE])
        Upgrade_Moodle 2>&1 | tee /root/upgrade_moodle${Upgrade_Date}.log
        ;;
    [eE][xX][iI][tT])
        exit 1
        ;;
    *)
        echo "Usage: ./upgrade.sh {nginx|mariadb|php|moodle}"
        exit 1
        ;;
esac
